<script setup>
import ChannelSelect from './ChannelSelect.vue'
import { Plus } from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { ref } from 'vue'
import request from '@/utils/request'

const visibleDrawer = ref(false) // 抽屉弹层 控制显示隐藏

// 默认数据
const defaultForm = {
  name: '',
  title: '', // 标题
  cate_id: '',
  cover_img: '', // 封面图片file对象
  content: '',
  state: '', // 状态
  base_salary: 0,
  phone: ''
}
//准备数据
const formModel = ref({ ...defaultForm })
//图片上传相关逻辑
const imgUrl = ref('')
const onUploadFile = (uploadFile) => {
  imgUrl.value = URL.createObjectURL(uploadFile.raw) // 预览图片
  formModel.value.cover_img = uploadFile.raw
}

//提交 发布文章
const emit = defineEmits(['success'])
const onPublish = async (state) => {
  console.log('formModel', formModel)
  await formRef.value.validate()

  // 当前接口需要 formData 对象
  // 转换 formData 数据
  // const fd = new FormData()
  // for (let key in formModel.value) {
  //   fd.append(key, formModel.value[key])
  // }
  // id存在，说明是编辑操作，需要回显
  let userUrl = formModel.value.id ? '/employee/update' : '/employee/add'
  let userData = formModel.value.id
    ? {
        id: formModel.value.id,
        address: '',
        basicSalary: formModel.value.base_salary,
        birthDate: '',
        dateOnBoard: '',
        email: '',
        loginName: formModel.value.phone,
        organizationId: formModel.value.cate_id,
        phone: formModel.value.phone,
        sex: '',
        userName: formModel.value.name
      }
    : {
        address: '',
        basicSalary: formModel.value.base_salary,
        birthDate: '',
        dateOnBoard: '',
        email: '',
        loginName: formModel.value.phone,
        organizationId: formModel.value.cate_id,
        phone: formModel.value.phone,
        sex: '',
        userName: formModel.value.name
      }
  request.post(userUrl, userData).then((res) => {
    console.log(res)
    if (res.data) {
      ElMessage({
        type: 'success',
        message: formModel.value.id ? '编辑成功' : '添加成功'
      })
      // 关抽屉
      visibleDrawer.value = false
      emit('success', formModel.value.id ? '' : 'add')
    }
  })
}

// 组件对外暴露一个方法 open,  基于 open 的参数，初始化表单数据，并判断区分是添加 还是 编辑
//1. open({ })                   =>  添加操作，添加表单初始化无数据
//2. open({ id: xx,  ...  })  =>  编辑操作，编辑表单初始化需回显
//open调用后，可以打开抽屉
const formRef = ref()
const editorRef = ref()

const open = (row) => {
  visibleDrawer.value = true // 显示抽屉
  if (row.id) {
    // 需要基于 row.id 发请求，获取要编辑的数据
    console.log('编辑回显')
    console.log('row', row)
    formModel.value = {
      ...row,
      name: row.userName,
      title: '', // 标题
      cate_id: row.organizationId,
      cover_img: '', // 封面图片file对象
      content: '',
      state: '', // 状态
      base_salary: row.basicSalary
    } // 添加：重置表单内容，编辑：回显数据
  } else {
    console.log('添加功能')
    formModel.value = { ...defaultForm } //重置数据表单数据
    // 但是img和文本编辑器需要手动重置
    imgUrl.value = ''
    // editorRef.value.setHTML('')
  }
  console.log(row)
}

const value = ref('')

const options = [
  {
    value: '0',
    label: '入职'
  },
  {
    value: '1',
    label: '离职'
  }
]

const rules = ref({
  name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  phone: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
    { min: 11, max: 11, message: '手机号长度为11位', trigger: 'blur' },
    { pattern: /^1[3456789]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  base_salary: [
    { required: true, message: '请输入基本工资', trigger: 'blur' },
    { pattern: /^[1-9]\d{0,9}(\.\d{1,2})?$/, message: '工资格式不正确', trigger: 'blur' }
  ]
  // cover_img: [{ required: true, message: '请选择头像', trigger: 'change' }]
})

defineExpose({
  open
})
</script>

<template>
  <el-drawer
    v-model="visibleDrawer"
    :title="formModel.id ? '编辑员工信息' : '添加员工信息'"
    direction="rtl"
    size="50%"
  >
    <!-- 发表文章表单 -->
    <el-form :model="formModel" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="formModel.name" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="formModel.phone" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="底薪" prop="base_salary">
        <el-input
          v-model="formModel.base_salary"
          type="number"
          placeholder="请输入员工底薪"
        ></el-input>
      </el-form-item>
      <el-form-item label="所属部门" prop="cate_id">
        <channel-select v-model="formModel.cate_id" width="100%"></channel-select>
      </el-form-item>
      <!-- <el-form-item :label="formModel.id ? '修改员工头像' : '添加员工头像'" prop="cover_img"> -->
      <!-- 此处需要关闭element-plus 的自动上传
             只需要做前端预览图片即可，不需要提前上传图片
             语法：URL.creatObjectURL(...)创建本地预览地址，来预览
        -->
      <!-- <el-upload
          class="avatar-uploader"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="onUploadFile"
        >
          <img v-if="imgUrl" :src="imgUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item> -->
      <!-- <el-form-item label="详细信息" prop="content"> -->
      <!-- <div class="editor">
          <quill-editor
            ref="editorRef"
            theme="snow"
            v-model:content="formModel.content"
            contentType="html"
          >
          </quill-editor>
        </div> -->
      <!-- <el-input v-model="formModel.content" rows="4" type="textarea"></el-input>
      </el-form-item> -->
      <el-form-item>
        <el-button @click="onPublish()" type="primary">添加</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
